from PyOEUO.game import Game
import sys,time

g=Game()  # Create a Game object taht represents our interface to the game

# Check that we are told which client to use (or it's the only one)
# CliCnt is a variable in game.dll that counts the number of active clients
# Variables can be accesed with g.VarName

try:
    myclient=int(sys.argv[1])
except:
    myclient=0

if g.CliCnt==0:
    print 'No running UO clients detected.'
    sys.exit(-1)
elif g.CliCnt>1 and (myclient<1 or myclient>g.CliCnt):
    print 'Multiple running UO clients detected.'
    print 'Please select one and run "%s <clinr>"'%sys.argv[0]
    for x in xrange(1,g.CliCnt+1):
        g.CliNr=x
        if g.CliLogged:
            print '%d) %s - %s (%s)'%(x,g.CharName,g.Shard,g.CliVer)
        else:
            print '%d) Not logged in (%s)'%(x,g.CliVer)
    sys.exit(-1)
elif g.CliCnt==1:
    myclient=1

g.CliNr=myclient # Select client
print 'Selected client: %s - %s (%s)'%(g.CharName,g.Shard,g.CliVer)

tCandle=2600        # Type IDs for candles
tLitCandle=2575

def ToggleCandle(candle,timeout=5):
    while True:
        started=time.time()
        candle.Use()
        while g.Item(candle.ID).Type==candle.Type and time.time()<started+timeout:
            # Here we wait until the candle changes its Type, or we reah timeout. Sleep for 0.1sec while waiting.
            time.sleep(0.1)
        if g.Item(candle.ID).Type<>candle.Type: # Did it change?
            break

for candle in g.FindItems(Type=tLitCandle,Dist=(0,2),ContID=0): # Find all lit candles on the ground
    ToggleCandle(candle)

for candle in g.FindItems(Type=tCandle,Dist=(0,2),ContID=0): # Find all unlit candles on the ground
    g.Drag(candle.ID,1) # Drag is a function in game.dll that initiate a Drag&Drop
    time.sleep(0.3)
    g.DropC(g.BackpackID,100,100) # Place in our backpack at 100,100
    time.sleep(0.3)

direction=-1

for candle in g.FindItems(Type=tCandle,ContID=g.BackpackID): # Find all candles in backpck
    g.Drag(candle.ID,1) # Drag is a function in game.dll that initiate a Drag&Drop
    time.sleep(0.1)
    g.DropG(g.CharPosX,g.CharPosY,g.CharPosZ) # Place on the ground below char
    time.sleep(0.1)
    ToggleCandle(candle)
    if not g.Move(g.CharPosX,g.CharPosY+direction,0,5000):
        direction*=-1 #if we failed to move - reverse direction
